<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-7-12
 * Time: 上午9:10
 */

namespace Application\Base;


class mdlResource
{
    static $application = "Base";

    /**
     * 获取有效的文件列表
     * @param $file
     * @return array
     */
    static function fileList($file)
    {
        $files = explode(";", $file);
        $application = array_shift($files);
        if (preg_match('/\w/', $application)) { //验证项目文件的合法性
            self::$application = $application;
        }
        $ext = self::ext($file);
        $lists = [];
        foreach ($files as $f) {
            $f = self::filter($f);
            $path = SYS_APPLICATION . $application . DIRECTORY_SEPARATOR . "static" . DIRECTORY_SEPARATOR . $f;
            if (!preg_match('/\.' . $ext . '$/', $path)) {
                $path .= "." . $ext;
            }
            if (file_exists($path)) {
                $lists[] = $path;
            }
        }
        return [$lists, $ext];
    }

    /**
     * 合并内容
     * @param $lists
     * @param $ext
     * @return string
     */
    static function merging($lists, $ext)
    {
        $content = "";
        if ($ext == 'css') {
            header("Content-Type:text/css;charset=utf-8");
            $content .= '@charset "utf-8";' . "\r\n";
        } else {
            header("Content-Type:text/javascript;charset=utf-8");
            $content .= '';
        }
        $lists = array_unique($lists);
        foreach ($lists as $list) {
            if (file_exists($list)) {
                $content .= "\r\n" . file_get_contents($list);
            }
        }
        return $content;
    }

    /**
     * 设置最后的文件修改时间
     * @param $lists
     */
    static function setLastModifyTime($lists)
    {
        $lastModifyTime = 0;
        foreach ($lists as $list) {
            $lastModifyTime = max(filemtime($list), $lastModifyTime);
        }
        $date = date("D, j M Y H:i:s ", $lastModifyTime) . 'GMT';
        header("Last-Modified: " . $date);
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
            if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $date) {
                header('HTTP/1.1 304 Not Modified');
                return;
            }
        }
    }

    /**
     * 获得文件类型
     * @param $file
     * @return string
     */
    static function ext($file)
    {
        if (preg_match('/.js$/', $file)) {
            return "js";
        } elseif (preg_match('/.css$/', $file)) {
            return "css";
        } else {
            mdlError::setError(mdlError::READ_GROUP_STATIC_ERROR);
        }
    }

    static function filter($file)
    {
        $file = str_replace("..", "", $file);
        $file = str_replace("/", DIRECTORY_SEPARATOR, $file);
        return $file;
    }

    static function ifSale()
    {

    }
} 